#-*- encoding: utf-8 -*-

"""
Yahoo Finance API - Quote
Read Stock Quote, this module just supports shanghai and shenzhen market.

"""

import urllib.request
import urllib.response
import urllib.error
import re
from data.YFACommon import *


# Quote Properties for return
QUOTE_PROPERTIES_1 = [\
    ("Symbol", "s"),\
    ("Name", "n"),\
    ("LastTradeDate", "d1"),\
    ("LastTradeTime", "t1"),\
    ("LastTradePriceOnly", "l1"),\
    ("Open", "o"),\
    ("PreviousClose", "p"),\
    ("DaysHigh", "h"),\
    ("DaysLow", "g"),\
    ("Volume", "v"),\
    ("AskRealtime", "b2"),\
    ("BidRealtime", "b3"),\
    ("Change", "c1"),\
    ("ChangeInPercent", "p2"),\
    ]

QUOTE_PROPERTIES_ALL = [\
    ("Symbol", "s"),\
    ("Name", "n"),\
    ("Open", "o"),\
    ("PreviousClose", "p"),\
    ("DaysHigh", "h"),\
    ("DaysLow", "g"),\
    ("AskRealtime","b2"),\
    ("BidRealtime", "b3"),\
    ("Volume", "v"),\
    ("Ask", "a"),\
    ("AskSize","a5"),\
    ("Bid", "b"),\
    ("BidSize", "b6"),\
    ("AverageDailyVolume", "a2"),\
    ("BookValuePerShare", "b4"),\
    ("Change", "c1"),\
    ("ChangeFromFiftyMovingAverage", "m7"),\
    ("ChangeFromTwoHundreddayMovingAverage", "m5"),\
    ("ChangeFromYearHigh", "k4"),\
    ("ChangeFromYearLow", "j5"),\
    ("ChangeInPercent", "p2"),\
    ("ChangeRealtime", "c6"),\
    ("Currency", "c4"),\
    ("LastTradeDate", "d1"),\
    ("LastTradeTime", "t1"),\
    ("LastTradePriceOnly", "l1"),\
    ("HighLimit", "l2"),\
    ("LowLimit", "l3"),\
    ("PercentChangeFromFiftydayMovingAverage", "m8"),\
    ("PercentChangeFromTwoHundreddayMovingAverage", "m6"),\
    ("ChangeInPercentFromYearHigh", "k5"),\
    ("PercentChangeFromYearLow", "j6"),\
    ("StockExchange", "x"),\
    ("YearHigh", "k"),\
    ("YearLow", "j"),\
    ("YearRange", "w"),\
    ("TwoHundreddayMovingAverage", "m4"),\
    ("LastTradeSize", "k3"),\
    ]

'''
    暂时无法或者不需要处理，会出现一些换行需要单独处理
    ("PricePaid", "p1"),\
    ("PriceSales", "p5"),\
    ("AfterHoursChange", "c8"),\
    ("Change_ChangeInPercent", "c"),\
    ("ChangeInPercentRealtime", "k2"),\
    ("DaysRange", "m"),\
    ("DaysRangeRealtime", "m2"),\
    ("DaysValueChange", "w1"),\
    ("DaysValueChangeRealtime", "w4"),\
    ("LastTradeRealtimeWithTime", "k1"),\
    ("LastTradeWithTime", "l"),\
    ("Commission", "c3"),\
    ("MarketCapitalization", "j1"),\
    ("MarketCapRealtime", "j3"),\
    ("MoreInfo", "i"),\
    ("Notes", "n4"),\
    ("OneyrTargetPrice", "t8"),\
    ("OrderBookRealtime", "i5"),\
    ("Revenue", "s6"),\
    ("SharesOwned", "s1"),\
    ("SharesOutstanding", "j2"),\
    ("ShortRatio", "s7"),\
    ("TradeDate", "d2"),\
    ("TradeLinks", "t6"),\
    ("TradeLinksAdditional", "f"),\
'''

def createProperties(props):
    p = ""
    for k, v in props:
        p = p+v
    #print(p)
    return p

def YFAQuote(ids, props=QUOTE_PROPERTIES_1):
    """ 使用Yahoo Finance API读取指定的股票实时数据，默认使用指定的返回数据信息，还可以指定数据配置，可以返回其他数据 """
    if ids==None or ids=="":
        return None

    if props==None:
        props = QUOTE_PROPERTIES_1


    params = { KEY_IDS: createIds(ids), KEY_PROPERTIES: createProperties(props), KEY_RT_FORMAT: VALUE_FORMAT_CSV }
    quoteUrl = BASE_RT_URL+"?"+urllib.parse.urlencode(params)    

    print(quoteUrl)


    try:
        #req = urllib.request.Request(quoteUrl, params) #, 10000)
        f = urllib.request.urlopen(quoteUrl) #, params)
        #data = f.read()
        #print(data)
        #dstr = str(data, "utf-8")
        #print(dstr)

        
        #'''
        line = f.readline()
        quotes = []
        while len(line)>0:
            #print(type(line))
            line = str(line, "utf-8")
            print(len(props))
            print(line)
            
            values = line.strip().split(",", len(props)-1)
            #index = 0
            #for ch in values[0]:
            #    index+=1
            #    print(index, ch)
            #print(len(line), values)
            index = 0
            data = {}
            for k, s in props:
                #k = props[index]
                if index<len(values):
                    v = checkStringValue(values[index])
                    print(k, v)
                    data[k] = v
                index += 1

            quotes.append((data[QUOTE_SYMBOL], data))

            line = f.readline()

        print(quotes)            

        # prepare to
        #'''

    except urllib.error.URLError as ue:
        print("Error: ", ue)
    

